<template>
  <div>
    <!-- 采购列表 -->
    <el-card class="purchase_card">
      <el-form :model="searchForm" ref="searchRef" inline>
        <el-form-item label="采购单号" prop="orderCode">
          <el-input
            v-model="searchForm.orderCode"
            placeholder="请输入采购单号"
            class="form_input"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="providerId">
          <el-select
            v-model="searchForm.providerId"
            class="form_input"
            placeholder="请选择供应商名称"
            filterable
          >
            <el-option
              v-for="item in providerList"
              :key="item.id"
              :label="item.providerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="getList()"
            class="btn"
          >
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleReset" class="btn">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt-1">
      <div class="w-full flex justify-end items-center mb-1">
        <el-button type="primary" icon="Plus" @click="openDrawer({ id: 0 })">
          新增
        </el-button>
      </div>

      <el-table :data="tableData" style="height: calc(100vh - 17rem)">
        <el-table-column prop="orderCode" label="采购单号" :width="180" fixed />
        <el-table-column
          prop="providerName"
          label="供应商名称"
          :width="150"
          fixed
        />
        <el-table-column prop="createUserName" label="制单人" :width="150" />
        <el-table-column prop="businessUserName" label="业务员" />
        <el-table-column
          prop="remark"
          label="采购内容"
          width="300"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-scrollbar style="height: 2rem">
              <el-alert
                :closable="false"
                v-for="(item, index) in row.remark"
                :key="index"
                class="w-full bg-[pink] mb-1"
              >
                {{ item }}
              </el-alert>
            </el-scrollbar>
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="采购金额">
          <template #default="{ row }">
            {{ row.paidAmount ? (row.paidAmount / 100).toFixed(2) : "0.00" }}
          </template>
        </el-table-column>
        <el-table-column prop="businessTime" label="采购时间" :width="180">
          <template #default="{ row }">
            {{ row.createdAt == 0 ? "/" : $initTime(row.createdAt * 1000, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="采购单状态">
          <template #default="{ row }">
            <span v-if="row.status == 1">
              <el-tag type="warning">草稿</el-tag>
            </span>
            <span v-else-if="row.status == 2"
              ><el-tag type="primary">已制单</el-tag></span
            >
            <span v-else-if="row.status == 3"
              ><el-tag type="success">已入库</el-tag></span
            >
            <span v-else-if="row.status == 4"
              ><el-tag type="danger">已废弃</el-tag></span
            >
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="制单时间" :width="180">
          <template #default="{ row }">
            {{ $initTime(row.createdAt * 1000, 2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="detailBtn(row)">
              <el-icon><InfoFilled /></el-icon>详情
            </el-button>
            <el-button
              type="primary"
              link
              @click="openDrawer(row)"
              v-if="row.status == 1"
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleAbandon(row.id)"
              v-if="row.status == 2 && row.inventoryCount == 0"
            >
              <el-icon><CloseBold /></el-icon>废弃
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row.id)"
              v-if="row.status == 1"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <PagingQuery
        :page="page"
        :pageSize="pageSize"
        :total="total"
        @getList="getList"
        class="mt-1"
      />
    </el-card>

    <!-- 1.详情 -->
    <el-drawer v-model="detail_drawer" destroy-on-close title="详情" size="75%">
      <DetailPage :detailForm="detailForm" />
    </el-drawer>

    <!-- 2.新增或者编辑 -->
    <el-drawer
      v-model="drawer"
      destroy-on-close
      :title="detail.id == 0 ? '新增采购单' : '编辑采购单'"
      size="90%"
    >
      <InsertUpdatePurchase
        :detailForm="detail"
        :providerList="providerList"
        :employeeList="employeeList"
        @handleBack="handleBack"
      />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import PagingQuery from "@/components/PagingQuery.vue";
import DetailPage from "./component/DetailPage.vue";
import InsertUpdatePurchase from "./component/InsertUpdatePurchase.vue";
import { handleApiResponse } from "@/utils/request.js";
import { GetProviderToOpticianList } from "../../../../wailsjs/go/api/GoodsApi";
import {
  GetGlassesStorePurchaseOrderList,
  DeleteGlassesStorePurchaseOrder,
  CancelGlassesStorePurchaseOrder,
} from "../../../../wailsjs/go/api/OrderApi";
import { GetOrganizeEmployeeList } from "../../../../wailsjs/go/api/CustomerApi";

onMounted(() => {
  getProviderList();
  getEmployeeList();
  getList();
});

const searchRef = ref(null);
const searchForm = ref({
  orderCode: "",
  providerId: null,
});

const handleReset = () => {
  searchRef.value.resetFields();
  getList();
};

const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
async function getList(e) {
  if (e) {
    page.value = e.page;
    pageSize.value = e.pageSize;
  }

  handleApiResponse(() =>
    GetGlassesStorePurchaseOrderList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm.value,
    })
  ).then((res) => {
    if (res.code == 0) {
      //   console.log(res);
      tableData.value = res.data.purchaseOrders || [];
      tableData.value.forEach((item) => {
        item.remark = item.remark.split("; ").filter(Boolean);
      });
      total.value = res.data.total || 0;
    }
  });
}

// 供货商列表
const providerList = ref([]);
async function getProviderList() {
  handleApiResponse(() =>
    GetProviderToOpticianList({
      page: 1,
      size: 1234,
    })
  ).then((res) => {
    if (res.code == 0) {
      providerList.value = res.data.providerToOpticianList || [];
    }
  });
}

// 业务员列表
const employeeList = ref([]);
async function getEmployeeList() {
  handleApiResponse(() =>
    GetOrganizeEmployeeList({ page: 1, pageSize: 1234 })
  ).then((res) => {
    if (res.code == 0) {
      employeeList.value = res.data.list || [];
    }
  });
}

// 1.详情
const detail_drawer = ref(false);
const detailForm = ref({});
const detailBtn = (row) => {
  detailForm.value = row;
  detail_drawer.value = true;
};

// 2.废弃
const handleAbandon = (id) => {
  ElMessageBox.confirm("你确定废弃这条数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() =>
      CancelGlassesStorePurchaseOrder({
        orderId: id,
      })
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success("废弃成功");
        getList();
      }
    });
  });
};
// 3.删除
const handleDelete = (id) => {
  ElMessageBox.confirm("你确定删除这条数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() => DeleteGlassesStorePurchaseOrder({ id })).then(
      (res) => {
        if (res.code == 0) {
          ElMessage.success("删除成功");
          getList();
        }
      }
    );
  });
};

// 4.新增或者编辑
const drawer = ref(false);
const detail = ref({});
const openDrawer = (row) => {
  detail.value = row;
  drawer.value = true;
};
const handleBack = (val) => {
  if (val == 1) {
    getList();
  }
  drawer.value = false;
};
</script>

<style scoped lang="scss">
.purchase_card {
  :deep(.el-form-item) {
    @apply mb-0;
  }
}
</style>